package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file1")
public class FileController1 {

    @PostMapping("/upload")
    public Result upLoad(MultipartFile file) {

        try {
            // 1.1判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }

            // 1.2获取文件的完整名
            String filename = file.getOriginalFilename();

            if (StringUtils.isEmpty(filename)) {
                throw new RuntimeException("文件不存在");
            }
            // 1.3获取文件的扩展名
            int i = filename.lastIndexOf(".");
            String exName = filename.substring(i + 1);


            // 1.4获取文件的内容
            byte[] bytes = file.getBytes();

            // 1.5创建文件上传封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(filename, bytes, exName);

            // 1.6上传文件
            String[] upload = FastDFSClient.upload(fastDFSFile);

            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];

            return new Result(true,StatusCode.OK,"文件上传成功",url);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.ERROR,"文件上传失败");


    }


}
